package mwa.cs.rq.ctrl;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;

import mwa.cs.dao.AddressDAO;
import mwa.cs.dao.MeterSizeDAO;
import mwa.cs.dao.RequestDAO;
import mwa.cs.dao.RequestQuoteDAO;
import mwa.cs.dao.RequestTypeDAO;
import mwa.cs.dao.UserLoginDAO;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS65001Srvl
 */
public class CS65001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;   
	private Database db;

	private String contactAddress;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS65001Srvl() {
        super();
    }
    
	public void processRequest(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
   		String vaProcessType = request.getParameter("methodType");
		if (vaProcessType.equals("getData")){
			getData(request, response);
		}
	}
    
    @SuppressWarnings({ "unchecked", "unused" })
    public void getData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
    	this.db = new Database();
    	RequestDAO voRequestDAO = new RequestDAO(db);
    	RequestQuoteDAO voRequestQuoteDAO = new RequestQuoteDAO(db);
    	RequestTypeDAO voRequestTypeDAO = new RequestTypeDAO(db);
    	AddressDAO voAddressDAO = new AddressDAO(db);
    	UserLoginDAO voUserLoginDAO = new UserLoginDAO(db);
    	MeterSizeDAO voMeterSizeDAO = new MeterSizeDAO(db);
    	List<Map<String , Object>> voListFindAll = null;
    	Map<String, Object> voMapRequest = new HashMap<String, Object>();
    	Map<String, Object> voMapRequestQuote = new HashMap<String, Object>();
    	DecimalFormat voFormatter = new DecimalFormat("#,###.00");
    	String vaRequestNumber = request.getParameter("requestNumber");
    	// Tab ข้อมูลผู้ยื่นคำร้อง
    	String vaAccount = "";
    	String vaApplicantName = "";
    	String vaContactHomeNumber = "";
    	String vaContactAddress = "";
    	String vaContactCity = "";
    	String vaContactDistrict = "";
    	String vaContactProvince = "";
    	String vaContactPostCode = "";
    	String vaContactTelephone = "";
    	// Tab ข้อมูลผู้ใช้น้ำ
    	String vaPName = "";
    	String vaFName = "";
    	String vaLName = "";
    	String vaCardId = "";
    	String vaHomeNumber = "";
    	String vaAddress = "";
    	String vaCity = "";
    	String vaDistrict = "";
    	String vaProvince = "";
    	String vaPostCode = "";
    	String vaTelephone = "";
    	// Tab ข้อมูลคำร้อง
    	String vaRequestType = "";
    	String vaDescription = "";
    	String vaAllowance = "";
    	String vaMeterInstallDate = "";
    	String vaMeterSize = "";
    	JSONArray voReceiveDescription = new JSONArray();
    	JSONArray voReceiveAmount = new JSONArray();
    	String vaStatus = "";
    	String vaInsertDate = "";
    	String vaUserId = "";
    	double vnTotalAmount = 0.00;
    	
    	voMapRequest = voRequestDAO.getAllRequestAllStatus(vnSiteId, vaRequestNumber);
    	
    	// set value tab ข้อมูลผู้ยื่นคำร้อง
    	if (voMapRequest.get("ACCOUNT") != null) {
    		vaAccount = "" + voMapRequest.get("ACCOUNT");
    	}
    	vaApplicantName = "" + voMapRequest.get("APPLICANT_NAME");
    	vaContactHomeNumber = "" + voMapRequest.get("CONTACT_HOME_NUMBER");
    	contactAddress = "" + voMapRequest.get("CONTACT_ADDRESS");
    	vaContactCity = voAddressDAO.getCityName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"), ""+ voMapRequest.get("CONTACT_DISTRICT_CODE"), ""+ voMapRequest.get("CONTACT_CITY_CODE"));
    	vaContactDistrict = voAddressDAO.getDistrictName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"), ""+ voMapRequest.get("CONTACT_DISTRICT_CODE"));
    	vaContactProvince = voAddressDAO.getProvinceName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"));
    	vaContactPostCode = "" + voMapRequest.get("CONTACT_POST_CODE");
    	vaContactTelephone = "" + voMapRequest.get("CONTACT_TELEPHONE");
    	request.setAttribute("account", vaAccount.equals("null") ? "" : vaAccount);
    	request.setAttribute("applicantName", vaApplicantName.equals("null") ? "" : vaApplicantName);
    	request.setAttribute("contactHomeNumber", vaContactHomeNumber.equals("null") ? "" : vaContactHomeNumber);
    	request.setAttribute("contactAddress", contactAddress.equals("null") ? "" : contactAddress);
    	request.setAttribute("contactCity", vaContactCity == null ? "" : vaContactCity);
    	request.setAttribute("contactDistrict", vaContactDistrict == null ? "" : vaContactDistrict);
    	request.setAttribute("contactProvince", vaContactProvince == null ? "" : vaContactProvince);
    	request.setAttribute("contactPostCode", vaContactPostCode.equals("null") ? "" : vaContactPostCode);
    	request.setAttribute("contactTelephone", vaContactTelephone.equals("null") ? "" : vaContactTelephone);
    	// set value tab ข้อมูลผู้ใช้น้ำ
    	vaPName = "" + voMapRequest.get("PNAME");
    	vaFName = "" + voMapRequest.get("FNAME");
    	vaLName = "" + voMapRequest.get("LNAME");
    	vaCardId = "" + voMapRequest.get("CARD_ID");
    	vaHomeNumber = "" + voMapRequest.get("HOME_NUMBER");
    	vaAddress = "" + voMapRequest.get("ADDRESS");
    	vaCity = voAddressDAO.getCityName(""+ voMapRequest.get("PROVINCE_CODE"), ""+ voMapRequest.get("DISTRICT_CODE"), ""+ voMapRequest.get("CITY_CODE"));
    	vaDistrict = voAddressDAO.getDistrictName(""+ voMapRequest.get("PROVINCE_CODE"), ""+ voMapRequest.get("DISTRICT_CODE"));
    	vaProvince = voAddressDAO.getProvinceName(""+ voMapRequest.get("PROVINCE_CODE"));
    	vaPostCode = "" + voMapRequest.get("POST_CODE");
    	vaTelephone = "" + voMapRequest.get("TELEPHONE");
    	request.setAttribute("pName", vaPName.equals("null") ? "" : vaPName);
    	request.setAttribute("fName", vaFName.equals("null") ? "" : vaFName);
    	request.setAttribute("lName", vaLName.equals("null") ? "" : vaLName);
    	request.setAttribute("cardId", vaCardId.equals("null") ? "" : vaCardId);
    	request.setAttribute("homeNumber", vaHomeNumber.equals("null") ? "" : vaHomeNumber);
    	request.setAttribute("address", vaAddress.equals("null") ? "" : vaAddress);
    	request.setAttribute("city", vaCity == null ? "" : vaCity);
    	request.setAttribute("district", vaDistrict == null ? "" : vaDistrict);
    	request.setAttribute("province", vaProvince == null ? "" : vaProvince);
    	request.setAttribute("postCode", vaPostCode.equals("null") ? "" : vaPostCode);
    	request.setAttribute("telephone", vaTelephone.equals("null") ? "" : vaTelephone);
    	// set value tab ข้อมูลคำร้อง
    	vaRequestType = voRequestTypeDAO.getRequestTypeForAskRequest(vnSiteId, ""+ voMapRequest.get("REQUEST_TYPE"));
    	vaDescription = "" + voMapRequest.get("DESCRIPTION");
    	vaAllowance = "" + voMapRequest.get("ALLOWANCE");
    	vaMeterInstallDate = "" + voMapRequest.get("METER_INSTALL_DATE");
    	vaMeterSize = voMeterSizeDAO.findDescriptionBySiteAndCode(vnSiteId,"" + voMapRequest.get("METER_SIZE"));
    	if (voMapRequest.get("STATUS").equals("1")) {
    		vaStatus = "รับคำร้อง";
    	} else if (voMapRequest.get("STATUS").equals("2")) {
    		vaStatus = "รับเงิน";
    	} else if (voMapRequest.get("STATUS").equals("3")) {
    		vaStatus = "ปิดคำร้อง";
    	} else {
    		vaStatus = "ยกเลิก";
    	} 
    	voListFindAll = voRequestQuoteDAO.searchRequestQuote(vnSiteId, vaRequestNumber);
    	if (voListFindAll.size() != 0) {
    		for (int i = 0; i < voListFindAll.size(); i++) {
    			voMapRequestQuote = voListFindAll.get(i);	
    			voReceiveDescription.add(voMapRequestQuote.get("DESCRIPTION"));
    			voReceiveAmount.add(voMapRequestQuote.get("RECEIVE_AMOUNT"));
    			vnTotalAmount += Double.parseDouble("" + voMapRequestQuote.get("RECEIVE_AMOUNT"));
        	}
    	}
    	vaInsertDate = "" + voMapRequest.get("INSERT_DATE");
    	vaUserId = voUserLoginDAO.findNameByUserId(vnSiteId, Integer.parseInt("" + voMapRequest.get("INSERT_USER_ID")));
    	request.setAttribute("requestNumber", vaRequestNumber);
    	request.setAttribute("requestType", vaRequestType.equals("null") ? "" : vaRequestType);
    	request.setAttribute("description", vaDescription.equals("null") ? "" : vaDescription);
    	request.setAttribute("allowance", vaAllowance.equals("1") ? "มีส่วนลด" : "ไม่มีส่วนลด");
    	request.setAttribute("meterInstallDate", vaMeterInstallDate.equals("null") ? "" : JDate.showDate(vaMeterInstallDate));
    	request.setAttribute("meterSize", vaMeterSize);
    	request.setAttribute("receiveDescription", voReceiveDescription);
    	request.setAttribute("receiveAmount", voReceiveAmount);
    	request.setAttribute("totalAmount", vnTotalAmount == .00 ? 0 : voFormatter.format(vnTotalAmount));
    	request.setAttribute("status", vaStatus);
    	request.setAttribute("insertDate", vaInsertDate.equals("null") ? "" : JDate.showDate(vaInsertDate));
    	request.setAttribute("userId", vaUserId);
    	
    	db.close();
    	RequestDispatcher rd = request.getRequestDispatcher("CS65001.jsp");
    	rd.forward(request, response);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
